package com.sky.aspect;


import com.sky.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoUpdateFillAspect {

    @Pointcut("@annotation(com.sky.annotation.AutoUpdatetFill)")
    public void pt() {

    }

    @Before("pt()")
    public void autoFill(JoinPoint joinPoint) {
        //1. 获取原始方法的参数
        Object[] args = joinPoint.getArgs();
        Object obj = args[0];
        //2. 给这个参数赋值
        try {
            // 获取方法对象

            Method setAgeMethod = obj.getClass().getMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = obj.getClass().getMethod("setUpdateUser", Long.class);
            // 调用方法赋值
            setAgeMethod.invoke(obj, LocalDateTime.now());
            Long currentId = BaseContext.getCurrentId();
            setUpdateUser.invoke(obj, currentId);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        }

    }


}
